import 'package:flutter/material.dart';
import '../models/morse_character.dart';
import '../services/morse_audio_service.dart';

class ToolboxPage extends StatefulWidget {
  const ToolboxPage({super.key});

  @override
  State<ToolboxPage> createState() => _ToolboxPageState();
}

class _ToolboxPageState extends State<ToolboxPage> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final MorseAudioService _audioService = MorseAudioService();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _audioService.stop();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF121212),
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Morse Code Reference',
          style: TextStyle(
            color: Colors.white,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: const Color(0xFF00BFFF),
          labelColor: const Color(0xFF00BFFF),
          unselectedLabelColor: const Color(0xFFAAAAAA),
          tabs: const [
            Tab(text: 'Letters'),
            Tab(text: 'Numbers'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildLettersTab(),
          _buildNumbersTab(),
        ],
      ),
    );
  }

  Widget _buildLettersTab() {
    return Container(
      color: const Color(0xFF121212),
      child: ListView.builder(
        padding: const EdgeInsets.all(20),
        itemCount: MorseData.letters.length,
        itemBuilder: (context, index) {
          final character = MorseData.letters[index];
          return _buildCharacterCard(character);
        },
      ),
    );
  }

  Widget _buildNumbersTab() {
    return Container(
      color: const Color(0xFF121212),
      child: ListView.builder(
        padding: const EdgeInsets.all(20),
        itemCount: MorseData.numbers.length,
        itemBuilder: (context, index) {
          final character = MorseData.numbers[index];
          return _buildCharacterCard(character);
        },
      ),
    );
  }

  Widget _buildCharacterCard(MorseCharacter character) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0xFF1E1E1E),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          // Character Display
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: const Color(0xFF333333),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Center(
              child: Text(
                character.character,
                style: const TextStyle(
                  fontSize: 24,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          
          const SizedBox(width: 20),
          
          // Morse Code Text
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  character.morseCode,
                  style: const TextStyle(
                    fontSize: 28,
                    fontFamily: 'monospace',
                    color: Color(0xFF00BFFF),
                    fontWeight: FontWeight.bold,
                    letterSpacing: 4,
                  ),
                ),
                const SizedBox(height: 8),
                _buildVisualMorse(character.elements),
              ],
            ),
          ),
          
          // Play Button
          GestureDetector(
            onTap: () => _playMorseCode(character),
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: const Color(0xFF00BFFF),
                borderRadius: BorderRadius.circular(20),
              ),
              child: const Icon(
                Icons.play_arrow,
                color: Colors.white,
                size: 24,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVisualMorse(List<MorseElement> elements) {
    return Row(
      children: elements.map((element) {
        if (element == MorseElement.dot) {
          return Container(
            margin: const EdgeInsets.only(right: 4),
            width: 8,
            height: 8,
            decoration: const BoxDecoration(
              color: Color(0xFF00BFFF),
              shape: BoxShape.circle,
            ),
          );
        } else {
          return Container(
            margin: const EdgeInsets.only(right: 4),
            width: 20,
            height: 6,
            decoration: BoxDecoration(
              color: const Color(0xFF00BFFF),
              borderRadius: BorderRadius.circular(3),
            ),
          );
        }
      }).toList(),
    );
  }

  Future<void> _playMorseCode(MorseCharacter character) async {
    if (_audioService.isPlaying) return;
    
    try {
      await _audioService.playCharacter(character);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Playing morse code for ${character.character}'),
          backgroundColor: const Color(0xFF00BFFF),
          duration: const Duration(milliseconds: 800),
        ),
      );
    }
  }
}
